package com.sunnada.edu.mobile.login.service;

import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sunnada.edu.system.login.service.RSAUtil;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.RSA;

public class PhoneLoginMethods {

	public static void setSession(HttpServletRequest request, Map map) {
		request.getSession().setAttribute(Constants.USER_ID_SESSION,
				map.get("USER_ID"));
		request.getSession().setAttribute(Constants.USER_NAME_SESSION,
				map.get("USER_NAME"));
		request.getSession().setAttribute(Constants.USER_TYPE,
				map.get("USER_TYPE"));
		request.getSession().setAttribute(Constants.USER_SHCHOOLID,
				map.get("SCHOOL_ID"));
		request.getSession()
				.setAttribute("SCHOOL_NAME", map.get("SCHOOL_NAME"));
		request.getSession().setAttribute("DEPT_ID", map.get("DEPT_ID"));
		request.getSession().setAttribute("DEPT_NAME", map.get("DEPT_NAME"));
		// 设置默认屏幕高度，用于分页自动算取每页记录数
		request.getSession().setAttribute(Constants.USER_SCREEN_HEIGHT, "280");

		String userType = (String) map.get("USER_TYPE");// 0：超级管理员 1：运维 2：代理
														// 3：学校
		// 如果系统登录用户是 "学校" 类型，则在session中添加teacherType 0:校长 1:年段长 2:班主任 3:课任老师
		// 4:后勤
		if ("3".equals(userType)) {
			String teacherType = PhoneLoginMethods.getTeacherType(map);
			request.getSession().setAttribute(Constants.TEACHER_TYPE,
					teacherType);
		}
	}

	/** 销毁session 2015-05-04 chs add */
	public static void removeSession(HttpServletRequest request) {
		request.getSession().removeAttribute(Constants.USER_ID_SESSION);
		request.getSession().removeAttribute(Constants.USER_NAME_SESSION);
		request.getSession().setAttribute(Constants.USER_ID_SESSION, null);
		request.getSession().setAttribute(Constants.USER_NAME_SESSION, null);
		request.getSession().setAttribute(Constants.USER_TYPE, null);
		request.getSession().setAttribute(Constants.USER_SHCHOOLID, null);
		request.getSession().setAttribute("SCHOOL_NAME", null);
		request.getSession().setAttribute("DEPT_ID", null);
		request.getSession().setAttribute("DEPT_NAME", null);
		request.getSession().setAttribute("TEACHER_TYPE", null);
		Enumeration em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
	}

	public static void reCheckcode(HttpServletRequest request) {
		int code = (int) ((Math.random() * 9 + 1) * 10000000);
		request.getSession().setAttribute("CheckCode", code);
	}

	public static String RSADecode(String password) {
		// password:加密长字符串(256)
		// 由于解密经常异常：若解密异常，将未加密的密码作为解密后的密码
		String pwd = password;
		try {
			password = org.apache.commons.lang.StringUtils.substring(pwd, 0,
					256);
			byte[] en_result = RSAUtil.hexStringToBytes(password);
			byte[] de_result = RSAUtil.decrypt(RSAUtil.getKeyPair()
					.getPrivate(), en_result);
			StringBuffer sb = new StringBuffer();
			sb.append(new String(de_result));
			password = sb.reverse().toString();
			password = URLDecoder.decode(password, "UTF-8");

			return password;
		} catch (Exception e) {
			e.printStackTrace();
			// logger.error("异常:RSA解密,密文:{}", pwd);
			return "";
		}
	}

	public static String RDecode(String pw) {
		try {
			return RSA.decrypt(pw, RSAUtil.getKeyPair().getPrivate());
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param params
	 * @return
	 */
	public static int updatePwd(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId = params.get("userId");
		String password = params.get("password");
		String sql = "update S_SYSUSER set  LOGIN_PWD='" + password
				+ "' where USER_ID='" + userId + "'";
		int num = dao.update(sql);
		return num;

	}

	/**
	 * 
	 * 设置学校
	 * 
	 * @param params
	 * @return
	 */
	public static int setSchool(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId = params.get("userId");
		String schoolId = params.get("schoolId");
		String sql = "update S_SYSUSER set  SCHOOL_ID='" + schoolId
				+ "' where USER_ID='" + userId + "'";
		int num = dao.update(sql);
		return num;

	}

	/**
	 * 
	 * 根据区域返回学校列表
	 * 
	 * @param params
	 * @return
	 */
	public static List getSchoolListByarea(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String areaCode = params.get("areaCode");
		String loginUserId = params.get("loginUserId");
		String sql = "SELECT T.SCHOOL_ID,T.SCHOOL_NAME FROM T_SCHOOL  T WHERE T.AREA_CODE like '"
				+ areaCode + "%' and t.REC_STATUS!='2'";
		if(!"admin".equals(loginUserId)){
			sql += "and (exists ( select distinct r.school_id from s_sysroleuser s left join s_sysrole r on s.role_id = r.rec_id where s.user_id = '"
					+ loginUserId
					+ "' and t.school_id = r.school_id or t.rec_person = '"
					+ loginUserId + "'))";
		}

		return dao.selectList(sql);
	}

	/**
	 * 
	 * 根据用户编号，功能按钮权限
	 * 
	 * @param params
	 * @return
	 */
	public static String getBtnStr(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String loginUserId = params.get("loginUserId");
		String sql = " SELECT distinct T1.LINK_PATH,T1.IS_MENU "
				+ " FROM S_SYSMODULE T1, S_SYSROLEUSER T2, S_SYSMODULEROLE T3 "
				+ " WHERE T1.REC_ID = T3.MODULE_ID "
				+ " AND T3.ROLE_ID = T2.ROLE_ID " + " AND T2.USER_ID ='"
				+ loginUserId + "' AND T1.REC_STATUS = '0' "
				+ " AND T1.is_menu = '3'";
		List<?> list = dao.selectList(sql);
		String btnStr = "";
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, String> d = (HashMap<String, String>) list.get(i);
			btnStr += d.get("LINK_PATH") + ";";
		}
		return btnStr;
	}

	public static List<?> getSysUser(String userLoginCode) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String sql = " select * from S_SYSUSER where USER_LOGINCODE='"
				+ userLoginCode + "'  and REC_STATUS='0'";
		return dao.selectList(sql);
	}

	public static String getTeacherType(Map params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId = (String) params.get("USER_ID");
		String sql = " select TEACHER_TYPE from t_teacher where teacher_id='"
				+ userId + "' ";
		List<?> list = dao.selectList(sql);
		String teacherType = "";
		if (list.size() > 0) {
			HashMap<String, String> d = (HashMap<String, String>) list.get(0);
			teacherType = d.get("TEACHER_TYPE");
		}
		return teacherType;
	}
	
	public static String getSchoolState(Map params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String SCHOOL_ID = (String)params.get("SCHOOL_ID");
		String sql = "select State from t_school where school_id='"+SCHOOL_ID+"'";
		List<?> list = dao.selectList(sql);
		HashMap<String, String> d = (HashMap<String, String>) list.get(0);
		return d.get("STATE");
	}
	
	public static String getSchoolStatus(Map params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String SCHOOL_ID = (String)params.get("SCHOOL_ID");
		String sql = "select REC_STATUS from t_school where school_id='"+SCHOOL_ID+"'";
		List<?> list = dao.selectList(sql);
		HashMap<String, String> d = (HashMap<String, String>) list.get(0);
		return d.get("REC_STATUS");
	}

}
